package cn.hzh.forward.service.impl;

import cn.hzh.forward.config.properties.FeishuConfigProperties;
import cn.hzh.forward.enums.MsgTypeEnum;
import cn.hzh.forward.service.FeishuMsgService;
import cn.hzh.forward.strategy.context.UploadStrategyContext;
import cn.hzh.forward.utils.ByteArrayMultipartFile;
import com.google.gson.Gson;
import com.google.gson.JsonParser;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;
import com.lark.oapi.Client;
import com.lark.oapi.core.utils.Jsons;
import com.lark.oapi.service.im.v1.model.*;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileWriter;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>飞书消息处理类</p>
 */
@Slf4j
@Component
@AllArgsConstructor
public class FeishuMsgServiceImpl implements FeishuMsgService {
    private final FeishuConfigProperties config;
    private final UploadStrategyContext uploadStrategyContext;

    private Client getClient() {
        return Client.newBuilder(config.getAppId(), config.getAppSecret()).build();
    }

    @Override
    public String handleMessage(P2MessageReceiveV1 event) {
        EventMessage message = event.getEvent().getMessage();
        String messageId = message.getMessageId();
        String messageType = message.getMessageType();
        log.info("parse message start, messageId: {}", messageId);
        // 解析消息
        String content = message.getContent();
        Map<String, String> respContent = new HashMap<>();
        try {
            respContent = new Gson().fromJson(content, new TypeToken<Map<String, String>>() {
            }.getType());
        } catch (JsonSyntaxException e) {
            respContent.put("text", "解析消息失败，请发送文本消息\nparse message failed, please send text message");
        }

        String result = null;

        // 组合消息
        if (MsgTypeEnum.POST.getType().equals(messageType)) {
            result = handleComplexMessage(messageId, content);
        }

        // 图片消息
        if (MsgTypeEnum.IMAGE.getType().equals(messageType)) {
            String imageKey = respContent.get("image_key");
            String imageUrl = handleImageMessage(messageId, imageKey);
            if (imageUrl != null) {
                result = "![图片](" + imageUrl + ")";
            }
        }

        // 文本消息
        if (MsgTypeEnum.TEXT.getType().equals(messageType)) {
            result = respContent.get("text");
        }
        return result;
    }

    @Override
    public String handleImageMessage(String messageId, String imageKey) {
        // 创建请求对象
        GetMessageResourceReq req = GetMessageResourceReq.newBuilder()
                .messageId(messageId)
                .fileKey(imageKey)
                .type("image")
                .build();
        GetMessageResourceResp resp;
        try {
            // 发起请求
            resp = getClient().im().v1().messageResource().get(req);
        } catch (Exception e) {
            log.error("handleImageMessage error: {}", e.getMessage());
            return null;
        }
        // 处理服务端错误
        if (!resp.success()) {
            log.error(String.format("code:%s,msg:%s,reqId:%s, resp:%s",
                    resp.getCode(), resp.getMsg(), resp.getRequestId(), Jsons.createGSON(true, false).toJson(JsonParser.parseString(new String(resp.getRawResponse().getBody(), StandardCharsets.UTF_8)))));
            return null;
        }

        // 创建 MultipartFile 对象
        MultipartFile multipartFile = new ByteArrayMultipartFile(
                resp.getData().toByteArray(),
                imageKey, // 表单字段名
                imageKey + ".png", // 文件名
                "image/png" // 根据实际图片类型调整
        );
        return uploadStrategyContext.executeUploadStrategy(multipartFile, "test/");
    }

    @Override
    public String handleComplexMessage(String messageId, String content) {
        // 1. 解析原始JSON
        Map<String, Object> rawMap = new Gson().fromJson(content, new TypeToken<Map<String, Object>>() {
        }.getType());
        List<List<Map<String, Object>>> messageContent = (List<List<Map<String, Object>>>) rawMap.get("content");

        StringBuilder result = new StringBuilder();

        // 2. 遍历处理每个内容块
        for (List<Map<String, Object>> contentBlock : messageContent) {
            for (Map<String, Object> element : contentBlock) {
                String tag = (String) element.get("tag");

                if ("text".equals(tag)) {
                    // 处理文本内容
                    result.append(element.get("text")).append("\n");
                } else if ("img".equals(tag)) {
                    // 处理图片内容
                    String imageKey = (String) element.get("image_key");
                    String imageUrl = handleImageMessage(messageId, imageKey);
                    if (imageUrl != null) {
                        result.append("![图片]").append("(").append(imageUrl).append(")\n");
                    }
                }
            }
        }

        return result.toString();
    }

    @Override
    public void handleHistoryMessage(String chatId) {
        log.info("handleHistoryMessage start...");

        ListMessageReq req = ListMessageReq.newBuilder()
                .containerIdType(chatId)
                .containerId(chatId)
                .build();
        try {
            ListMessageResp resp = getClient().im().message().list(req);
            if (!resp.success()) {
                throw new Exception(String.format("client.im.message.list failed, code: %d, msg: %s, logId: %s",
                        resp.getCode(), resp.getMsg(), resp.getRequestId()));
            }
            File file = new File("feishu.chat_history.txt");
            FileWriter writer = new FileWriter(file);
            for (Message item : resp.getData().getItems()) {
                String senderId = item.getSender().getId();
                String content = item.getBody().getContent();
                String createTime = item.getCreateTime();
                log.info("[list-message-resp]={}", item.getBody().getContent());
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                createTime = sdf.format(new Date(Long.parseLong(createTime)));
                writer.write(String.format("chatter(%s) at (%s) send: %s\n", senderId, createTime, content));
            }
            writer.close();
        } catch (Exception e) {
            log.error("handleHistoryMessage error: {}", e.getMessage());
        }
    }
}